package controller.register;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.User;
import service.user.UserService;
import service.user.UserServiceImpl;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/register")
public class RegisterController {
    @RequestMapping(method = RequestMethod.GET)

    //Get方法用来跳转页面
    public String register(Model model, HttpSession session) {
        if (session.getAttribute("id") != null) {
            session.removeAttribute("id");
        }
        return "../../register";
    }

    //自动装配User
    @Autowired
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public Map<String, String> isRegister(@RequestBody Map<String, String> info, HttpSession session, HttpServletResponse response) {
        System.out.println(info);
        User user = new User();
        user.setCid(info.get("cid"));
        user.setPassword(info.get("password"));
        user.setPhone(info.get("phone"));
        user.setNumber(info.get("number"));
        Map<String, String> toRegister = new HashMap<>();
        int i = -1;
        try {
            i = userService.registerUser(user);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        if (i > 0) {
            System.out.println(user);
            System.out.println("Register Success");

            toRegister.put("info", "注册成功,现在可以进行登录了！");
            return toRegister;
        } else {
            System.out.println("Register Failed");
            toRegister.put("info", "此ID或身份证号已被占用！");
            return toRegister;
        }

    }
}